<template>
    <div class="user">
        <div class="dept">
            <div class="head-title">所属部门</div>
            <!-- <el-button type="success" plain @click="toggleRowExpansion" size="small">全部展开/收缩</el-button> -->
            <div class="dept-content">
                <el-tree node-key="id" style="max-width: 600px" :data="deptOptions" @node-click="handleNodeClick"
                    ref="treeRef" :expand-on-click-node="false" />
            </div>
        </div>
        <div class="user-box">
            <div class="user-head">
                <div class="head-title">用户列表</div>
                <div class="user">
                    <el-button class="head-btn" type="primary" plain @click="addUser"><i
                            class=" iconfont icon-tianjia"></i>
                        新增用户</el-button>
                    <div class="option">
                        <el-input v-model="search" placeholder="请输入用户名称" class="input">
                            <template #append>
                                <el-button class="iconfont icon-sousuo3" @click="searchByTitel"></el-button>
                            </template>
                        </el-input>
                    </div>
                </div>
            </div>
            <div class="table">
                <el-table :data="tableData" style="width: 100wh" @selection-change="selectUserId"
                    :header-cell-style="{ 'text-align': 'center', background: '#f0f4f7', color: '#606266' }"
                    max-height="450" :row-style="{ height: '5vh' }">
                    <!-- <el-table-column type="selection" width="35" align="center" /> -->
                    <el-table-column label="序号" type="index" width="80" align="center" />
                    <el-table-column prop="userName" label="用户名" max-width="180" min-width="100px" align="center"
                        :show-overflow-tooltip="true">
                    </el-table-column>
                    <el-table-column prop="stuId" label="学号" max-width="100" align="center"
                        :show-overflow-tooltip="true" />
                    <!-- <el-table-column prop="createTime" label="创建时间" max-width="150" min-width="100px" align="center" /> -->
                    <el-table-column prop="status" label="状态" max-width="100" align="center">
                        <template #default="scope">
                            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" inline-prompt
                                active-text="正常" inactive-text="禁用" @change="changeStatus(scope.row)"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" min-width="90px">
                        <template #default="scope">
                            <el-tooltip class="box-item" effect="dark" content="编辑用户信息"
                                placement="bottom">
                                <el-button type="primary" circle class="iconfont icon-bianji"
                                    @click="updateUserBtn(scope.row)" />
                            </el-tooltip>

                            <el-popconfirm width="120" confirm-button-text="确认" cancel-button-text="取消"
                                @confirm="deleteUser(scope.row)" title="确认删除?">
                                <template #reference>
                                    <el-button type="danger" circle class="iconfont icon-shanchu" />
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="foot">
                <div class="question-foot">
                    <el-pagination v-model:current-page="paginationData.pageNum"
                        v-model:page-size="paginationData.pageSize" :page-sizes="[20, 50, 100]"
                        :small="paginationData.small" layout="sizes, prev, pager, next"
                        :total="Number(paginationData.total)" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" class="pagination" />
                </div>
            </div>

            <el-dialog v-model="visibleDialog" width="40%" draggable class="dialog">
                <template #header class="dialog-header">
                    <div v-if="dialogHeader == 1">新增用户</div>
                    <div v-if="dialogHeader == 2">修改用户信息</div>
                </template>
                <el-form label-position="left" :model="userData" label-width="auto" class="dialog-form">
                    <div class="form-horizontal">
                        <el-form-item label="用户名">
                            <el-input v-model="userData.userName" placeholder="请输入用户名" />
                        </el-form-item>
                        <el-form-item label="姓名">
                            <el-input v-model="userData.name" placeholder="请输入姓名" />
                        </el-form-item>
                    </div>
                    <div class="form-horizontal">
                        <el-form-item label="手机号">
                            <el-input v-model="userData.phone" placeholder="请输入手机号" />
                        </el-form-item>
                        <el-form-item label="密码">
                            <el-input v-model="userData.password" placeholder="请输入密码" />
                        </el-form-item>
                    </div>
                    <div class="form-horizontal">
                        <el-form-item label="学号">
                            <el-input v-model="userData.stuId" placeholder="请输入描述" />
                        </el-form-item>
                        <el-form-item label="描述">
                            <el-input v-model="userData.description" placeholder="请输入描述" />
                        </el-form-item>
                    </div>
                    <el-form-item label="性别" class="change-row">
                        <el-select v-model="userData.sex" placeholder="请选择性别" style="width: 200px">
                            <el-option v-for="item in options" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属部门" v-if="dialogHeader == 1" class="change-row">
                        <el-cascader :options="deptOptions" v-model="userData.deptId" :props="{ checkStrictly: true }"
                            ref="cascaderRef" :show-all-levels="false" filterable class="cascader" />
                    </el-form-item>
                    <el-form-item label="头像" class="description">
                        <el-input v-model="userData.avatar" placeholder="请选择头像" />
                    </el-form-item>
                    <!-- <el-form-item label="用户状态" class="status">
                    <template #default>
                        <el-switch v-model="userData.status" :active-value="1" :inactive-value="0" inline-prompt
                            active-text="正常" inactive-text="禁用"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </template>
                </el-form-item> -->
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="saveSysUser(userData)" class="dialog-btn"
                            v-if="dialogHeader == 1">确定</el-button>
                        <el-button type="primary" @click="updateSysUser(userData)" class="dialog-btn"
                            v-if="dialogHeader == 2">保存</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>


</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { findByPageAPI, findNodesAPI, saveSysUserAPI, deleteUserByIdAPI, updateSysUserAPI, getUserBudeptIdAPI } from '@/api/api.js'
import { ElMessage } from 'element-plus';

//联级选择框
const cascaderRef = ref()
//对话框是否弹出
const visibleDialog = ref(false)
//弹框标题
const dialogHeader = ref()
//表格数据
const tableData = ref()
//新增 修改用户信息
const userData = ref({
    userName: '',
    name: '',
    phone: '',
    password: '',
    avatar: '',
    description: '',
    stuId: '',
    sex: '',
    // status: '',
    deptId: '',
})
//修改的部门id
const deptId = ref()
//部门名
const deptOptions = ref([])
//搜索栏
const search = ref('')
//默认展开行 
const isExpand = ref(false)
const treeRef = ref()
//变量
const flag = ref(false)
//题目分页
const paginationData = reactive({
    pageSize: 20,
    total: 0,
    pageNum: 1,
    background: false,
    disabled: false,
    small: '',
})
//性别
const options = ref([
    {
        label: '女',
        value: 1,
    },
    {
        label: '男',
        value: 0,
    },
])
onMounted(() => {
    //获取用户列表
    findByPage()
    //获取部门信息
    findNodes()
})

//获取用户列表
const findByPage = async () => {
    await findByPageAPI(paginationData.pageNum, paginationData.pageSize, search.value).then(res => {
        console.log(search.value);
        tableData.value = res.data.data.list
        console.log(res.data.data.list, '========');
    })
}
//获取所有部门信息
const findNodes = async () => {
    await findNodesAPI().then(res => {
        if (res.data.code) {
            deptOptions.value = getTreeData(res.data.data)
        }
    })
}
//获取树形部门
const getTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
        data[i].label = data[i].deptName
        data[i].value = data[i].id
        if (data[i].children == null || data[i].children.length < 1) {
            data[i].children = undefined     //避免children为空的时候，下一级显示为空白
        }
        else {
            getTreeData(data[i].children)
        }
    }
    return data
}
//根据部门查找用户
const handleNodeClick = async (data) => {
    flag.value = true
    const deptId = data.id
    await getUserBudeptIdAPI(deptId, paginationData.pageNum, paginationData.pageSize).then(res => {
        tableData.value = res.data.data.list
    })
}

// 切换数据表格树形展开(未实现)
const toggleRowExpansion = () => {
    isExpand.value = !isExpand.value
    toggleRowExpansionAll(deptOptions.value, isExpand.value);
}
const toggleRowExpansionAll = (data, isExpand) => {
    data.forEach((item) => {
        treeRef.value.toggleRowExpansion(item, isExpand);
        if (item.children !== undefined && item.children !== null) {
            toggleRowExpansionAll(item.children, isExpand);
        }
    });
}

//当一页的数量改变
const handleSizeChange = (newPageSize) => {
    paginationData.pageSize = newPageSize
    getQueryBankListCourse(sessionStorage.getItem('courseId'))
}
//第几页
const handleCurrentChange = (newCurrentPage) => {
    paginationData.pageNum = newCurrentPage
    getQueryBankListCourse(sessionStorage.getItem('courseId'))
}
//新增用户按钮
const addUser = () => {
    userData.value = {}
    visibleDialog.value = true
    dialogHeader.value = 1

}
//新增用户
const saveSysUser = async (data) => {
    if (data.deptId) {
        if (data.deptId.length > 1) {
            data.deptId = Object.values(data.deptId).pop()
        }
        data.deptId = parseInt(data.deptId)
    }
    data.phone = parseInt(data.phone)
    data.password = parseInt(data.password)
    data.stuId = parseInt(data.stuId)
    await saveSysUserAPI(data).then(res => {
        if (res.data.code == 200) {
            visibleDialog.value = false
            ElMessage.success('添加用户成功')
            //获取用户列表
            findByPage()
        }else {
            ElMessage.warning(res.data.message)
        }
    })
}
//更新按钮
const updateUserBtn = (row) => {
    console.log(row, 'row111111');
    userData.value = row
    // userData.value.deptId = row.deptId.split()
    visibleDialog.value = true
    dialogHeader.value = 2
}
//更新用户
const updateSysUser = async (data) => {
    await updateSysUserAPI(data).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('更新成功')
            visibleDialog.value = false
        }
        else {
            ElMessage.warning(res.data.message)
        }
    })
}
//批量获取用户id
const selectUserId = () => {

}
//修改用户状态
const changeStatus = (row) => {
    updateSysUser(row)
    console.log(row);
}
//根据关键词搜索用户
const searchByTitel = () => {
    findByPage()
    // console.log(flag.value);
    // if (flag.value) {
    //     handleNodeClick(data)
    // } else {
    //     findByPage()
    // }
}
//删除用户
const deleteUser = async (row) => {
    const userId = row.id
    await deleteUserByIdAPI(userId).then(res => {
        if (res.data.code) {
            ElMessage.success('删除成功')
            //获取用户列表
            findByPage()
        }else {
            ElMessage.warning(res.data.message)
        }
    })
}

</script>

<style lang="less">
.el-dialog__header {
    margin: 0 !important;
    background-color: #f8f8f8 !important;
    border-bottom: 1px solid #eeeeee;
}

.el-dialog__footer {
    background-color: #f0f4f7 !important;
    padding: 10px !important;
    border-top: 1px solid #eeeeee;
}

.cascader {
    width: 200px !important;
}
</style>
<style lang="less" scoped>
.user {
    display: flex;

    .dept {
        width: 200px;
        background-color: #fff;
        margin: 15px 20px 0 0;

        .head-title {
            font-size: 18px;
            font-weight: 550;
            color: grey;
            padding: 15px 10px 0px 10px;
        }

        .dept-content {
            margin: 10px;
        }

        ::v-deep .el-tree-node.is-current>.el-tree-node__content {
            color: #409eff !important;
        }


    }

    .user-box {
        padding: 0;
        margin: 15px 0px 0 0;
        background-color: #fff;
        // border-radius: 15px;
        width: 1150px;

        .user-head {
            .head-title {
                font-size: 18px;
                font-weight: 550;
                color: grey;
                padding: 15px 10px 0px 10px;
            }

            .user {
                display: flex;
                justify-content: end;
                margin: 10px 5px 0px 5px;
                font-size: small;

                .option {
                    display: flex;
                    margin: 10px 10px 20px 10px;

                    .option-word {
                        margin-top: 2px;
                        padding: 3px 7px;
                        font-size: 14px;
                    }

                    .select {
                        width: 130px;
                    }

                    .input {
                        width: 240px;

                    }
                }

                .head-btn {
                    margin: 10px 15px 0 5px;
                }
            }

        }

        .table {
            max-height: 66vh;
            min-height: 66vh;
            margin: auto;
            width: 1050px;
        }

        .foot {
            overflow: hidden;
            display: flex;
            justify-content: center;

            .question-foot {
                display: flex;
                justify-content: center;

                .pagination {
                    margin-bottom: 10px;

                }

            }
        }
    }
}




.dialog {
    width: 100px;

    .dialog-form {
        margin: 0 auto;

        .form-horizontal {
            display: flex;
            justify-content: space-around;
            flex-direction: row;

        }

        .change-row {
            margin-left: 12px;
        }

        .status {
            margin-left: 9px;
        }

        .description {
            margin-left: 9px;
            width: 400px;
        }

    }


    .dialog-footer {
        display: flex;
        justify-content: end;
        margin-right: 20px;

        .dialog-btn {
            margin-top: 0;
            width: 80px;
        }
    }


}
</style>